package com.quanshu.exchange.ui.gui.message.friends;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 我的好友
 * Created by xiniu003 on 2017/12/7.
 */

public class MyFriendListActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.search_btn)
    ImageView searchBtn;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.label_rel)
    RelativeLayout labelLayout;

    private List<UserEntity> userEntityList;
    private SingleAdapter<UserEntity> adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myfriend);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter<>(new DataDisplayer<UserEntity>(this, R.layout.item_friend_layout) {
            @Override
            public void bindData(BaseViewHolder holder,
                                 LayoutWrapper<UserEntity> wrapper,
                                 UserEntity item,
                                 int position) {
                holder.setRoundImageUrl(R.id.item_contacts_icon, item.getAvatar(), R.drawable.default_avatar);
                holder.setText(R.id.item_contacts_title, AppUtils.getUserName(item));
                String letter = AppUtils.getUserInitialLetter(item);
                // 处理分割线
                int nextPosition = position + 1;
                if (nextPosition < userEntityList.size()) {
                    UserEntity nextUser = userEntityList.get(position + 1);
                    String nextHead = AppUtils.getInitialLetter(AppUtils.getUserName(nextUser));
                    if (letter.equals(nextHead)) {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.VISIBLE);
                    } else {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.GONE);
                    }
                }
                if (position == userEntityList.size() - 1) {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.VISIBLE);
                } else {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.GONE);
                }
                // 处理head字母
                if (position == 0) {
                    holder.setVisibility(R.id.item_contacts_sort_letter, View.VISIBLE);
                    holder.setText(R.id.item_contacts_sort_letter, letter);
                } else {

                    int lastPosition = position - 1;
                    if (lastPosition < 0) {
                        lastPosition = 0;
                    }
                    UserEntity lastUser = userEntityList.get(lastPosition);
                    if (letter.equals(AppUtils.getUserInitialLetter(lastUser))) {
                        holder.setVisibility(R.id.item_contacts_sort_letter, View.GONE);
                    } else {
                        holder.setVisibility(R.id.item_contacts_sort_letter, View.VISIBLE);
                        holder.setText(R.id.item_contacts_sort_letter, letter);
                    }
                }
                holder.setOnClickListener(view -> {
                    Intent intent = new Intent(MyFriendListActivity.this, PrivateChatDetailActivity.class);
                    intent.putExtra("UserEntity", item);
                    startActivityForResult(intent, 0x02);
                });
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void initData() {
        userEntityList = UserDao.getInstance().queryForAll();
        if (userEntityList != null) {
            AppUtils.sortDataByPinYin(userEntityList);
            adapter.setData(userEntityList);
        }
        asyncFetchContactsFromServer();
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(searchBtn, aVoid -> goSearchActivity());
        RxViewHelper.getInstance().clicks(labelLayout, aVoid -> goLabelListActivity());
    }

    private void goLabelListActivity() {
        if (userEntityList == null || userEntityList.isEmpty()) {
            ToastHelper.toast("还没有好友，请先找寻小伙伴吧");
            return;
        }

        Intent intent = new Intent(this, FriendLabelListActivity.class);
        intent.putExtra("List<UserEntity>", (Serializable) userEntityList);
        startActivity(intent);
    }

    private void goSearchActivity() {
        Intent intent = new Intent(this, SearchUserActivity.class);
        startActivity(intent);
    }

    private void asyncFetchContactsFromServer() {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getFriendList(AppUtils.getSignParams(currentUser.getMemberid()), currentUser.getMemberid())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<List<UserEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<UserEntity>> response) {
                        userEntityList = response.getInfo();
                        UserDao.getInstance().save(userEntityList);
                        if (userEntityList != null) {
                            AppUtils.sortDataByPinYin(userEntityList);
                            adapter.setData(userEntityList);
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x02) {
                initData();
            }
        }
    }
}
